<?php
/**
 * <b>RUBIK IT Solution & Development ltd.</b>
 *
 * PROJECT		: Auction
 * @version 	: 1.0
 * COPYRIGHT    : 2010
 * ------------------------------------------------------
 *
 * Created on	:  Sep 20, 2010
 *
 */

// no direct access
defined ( '_FW_EXEC' ) or die ( 'Restricted access' );

RCoreImporter::cls( "mvc.AbstractController" );
RClassesImporter::cls('controllers.AbstractUserController');
RClassesImporter::cls('dbo.dtos.MemberDTO');
SysApplication::importModelCls('UsersModel');

require_once 'class.phpmailer.php';		
require_once 'class.smtp.php';
require_once 'class.pop3.php'; 
define('GUSER', 'namvo1988@gmail.com');          // Email
define('GPWD', 'vovinhnam852134');                 // Password
/**
 * Description of UsersFrontController
 *
 */
class UsersFrontController extends AbstractUserController{
	/**
	 * @var UsersModel
	 */
	var $_model;

	function __construct() {
		parent::__construct();
		$this->_model = new UsersModel();
		$root = SYS_ROOT_URL;
	}

	function display() {
		$this->setRedirect(SYS_ROOT_URL);
	}

	function login() {
		if (SysAuthenticate::isLogged()) {
			$this->setRedirect(SYS_ROOT_URL);
			return;
		}
		$this->setRedirect(SystemSite::urlRoute('?app=authenticate&act=login'));
	}


	function _warning($msg = null) {
		$msg = HTMLHelper::createMessageWarning($msg);
		eval('echo "'.SysApplication::loadTemplate('front/warning').'";');
	}

	/**
	 * (non-PHPdoc)
	 * @see classes/controllers/AbstractX4youController#execute($task, $useDefault)
	 */
	function execute($task, $useDefault = true) {
		if ($this->_modelDTO) {
			$this->_setSessionUserInfo(null);
		}
		parent::execute($task, $useDefault);
	}

	function register(){
		require SysApplication::getTemplatePath('front/signup');
	}

	function registertobuy1() {
		return $this->register1(GROUP_BUYER);
	}

	function registertocompany() {
		require SysApplication::getTemplatePath('front/signup-company');
	}

	function registerToCompanyFree1() {
		$this->register1(GROUP_FREE_MEMBER, 'registerToCompany2.php');
	}

	function registerToCompanyPaid1() {
		$this->register1(GROUP_PAYMENT_MEMBER, 'registerToCompany2.php');
	}

	function register1($userGroup = GROUP_BUYER,$nextStep = 'registertobuy2.php') {
		if (!$isEdit && SysRequest::getMethod() == 'POST') {
			$msg = $this->processRegStep1();
			if ($msg === true) {
				$this->setRedirectToFunction($nextStep);
			}
			else {
				$this->setRedirectToCurrentFunction($msg);
			}
			return;
		}

		$msg = $this->_getMsg();

		$this->_getSessionUserInfo($userDto);

		RExtImporter::cls('jscalendar.JsCalendarDateHtmlFieldInfo');
		$jsCtrl = new JsCalendarDateHtmlFieldInfo('birthday');
		$jsCtrl->setValue($userDto);
		$birthdayHtml = $jsCtrl->getHtmlInputData();

		$state = $this->_getState();
		$link_app = SystemSite::urlRoute('?app=users&act=getCityOfState');
		$link_app2 = SystemSite::urlRoute('?app=users&act=checkExistUser');
		$photoURL = $userDto->photo;
		if ($photoURL != ""){
			$photoURL = '<img src="'.RubikHelper::checkAndAddImageURL($photoURL).'" alt="Towing Auction Avatar" height="103" width="110"/>';
		} else {
			$photoURL = $this->_getHtmlPicturesHtmls($userDto);
		}
		 
		$photoHTML = $this->_getHtmlPicturesHtmls($userDto);
		$regHeader = $this->_getRegHeader(1, $userGroup);

		require SysApplication::getTemplatePath('front/reg/signuptobuy1');
	}

	function _getRegHeader($step, $userGroup) {
		$stepType = 3;
		switch ($userGroup) {
			case GROUP_BUYER:
				$regTitle =  SysDBLanguage::_('REGISTER TO BUY');
				if ($step == 4) {
					$step = 3;
				}
				break;
			case GROUP_FREE_MEMBER:
				if ($step == 4) {
					$step = 3;
				}
				$regTitle =  SysDBLanguage::_('REGISTER AS COMPANY - free');
				break;
			case GROUP_PAYMENT_MEMBER:
				$regTitle =  SysDBLanguage::_('REGISTER AS COMPANY - paid');
				$stepType = 4;
				break;
		}

		ob_start();
		require SysApplication::getTemplatePath("front/reg/{$stepType}stepsHeader");
		$result = ob_get_contents();
		ob_end_clean();
		return $result;
	}

	function registerToCompany2() {
		return $this->register2(null);
	}

	function registertobuy2() {
		return $this->register2();
	}

	function register2($userGroup = GROUP_BUYER) {
		$this->_getSessionUserInfo($userDto);
		if ($userGroup == null) {
			$userGroup = $userDto->user_group_code;
		}

		switch ($userGroup) {
			case GROUP_FREE_MEMBER:
				$nextStep = 'saveRegister';
				$backStep = 'registerToCompanyFree1.php';
				break;
			case GROUP_PAYMENT_MEMBER:
				$nextStep = 'registerToCompanyPaid3.php';
				$backStep = 'registerToCompanyPaid1.php';
				break;
			case GROUP_BUYER:
			default:
				$nextStep = 'saveRegister';
				$backStep = 'registertobuy1.php';
				break;
		}

		if (!$isEdit && SysRequest::getMethod() == 'POST') {
			$msg = $this->processRegStep1();
			if ($msg === true) {
				if ($_POST['saveBtn'] == 'prev') {
					$this->setRedirectToFunction($backStep);
					return;
				}
				else if ($_POST['saveBtn'] == 'next') {
					$this->setRedirectToFunction($nextStep);
					return;
				}
			}
			$this->setRedirectToCurrentFunction($msg);
			return;
		}
		$tmpUrl = SYS_CUR_TMPL_URL;
		$msg = $this->_getMsg();
		//		$this->_getSessionUserInfo($userDto);
		$state = $this->_getAState($userDto->state_id);
		$city = $this->_getACity($userDto->city_id);
		$photo = $userDto->photo;
		if ($photo != ""){
			$photo = RubikHelper::checkAndAddImageURL($photo);
		} else {
			$photo = RubikHelper::checkAndAddImageURL(SYS_CUR_TMPL_URL."images/blank-avatar.png");
		}

		$regHeader = $this->_getRegHeader(2, $userGroup);
		 
		require SysApplication::getTemplatePath('front/reg/signuptobuy2');
	}

	function registerToCompanyPaid3() {
		//    	$msg = $this->_saveRegiger(true);
		//    	if ($msg === true) {
		$regHeader = $this->_getRegHeader(3, GROUP_PAYMENT_MEMBER);
		$cancelUrl = $this->getLinkToFunction('registerToCompanyPaid3.php');
		$returnUrl = $this->getLinkToFunction('saveRegister');
		require SysApplication::getTemplatePath('front/reg/signup-pay');
		//    	}
		}

		function saveRegister(){
			// Save
			$msg = $this->_saveRegiger(false);

			if ($msg === true) {
				$this->setRedirectToFunction('thankyou');
				return;
			} else  {
				echo $msg;
			}
		}

		function _saveRegiger($isSaveOnly = false) {
			$this->_getSessionUserInfo($userDto);
			if (!$userDto) {
				if (!$isSaveOnly) {
					$this->setRedirect(SYS_ROOT_URL);
				}
				return true;
			}
			$activationCode = RStringHelper::generateRandom(32);
			$userDto->activation_code = $activationCode;

			$resu = SysDatabase::saveDTO($userDto);
			if(!$resu){
				RubikHelper::debugPrePrint($userDto);
				//luu vao DB gap loi
				return $userDto->getAllErrorsMsg();
			} else {
				// Send the email for activation
				$userName = base64_encode($userDto->username);
				$activationCode = base64_encode($userDto->activation_code);
				$activeLink = SystemSite::urlRoute("?app=users&act=active&activateCode={$activationCode}&ref={$userName}");
				eval('$mailBody ="'.SysApplication::loadTemplate('front/reg/mail.register').'";');

				RCoreImporter::cls('helper.RMailHelper');
				$this->_setSessionUserInfo(null);	//xoa bo cac SESSION

				$_SESSION['__USER_GROUP_'] = $userDto->user_group_code;

				if (RMailHelper::sentMail($userDto->email, "Register and activation information from Auction.Com", $mailBody)){
					return true;
				} else {
					return "mail-false";
				}
			}
			$this->_setSessionUserInfo(null);
			return true;
		}

		/* After register success
		 *
		 */
		function thankyou() {
			$userGroup = SysRequest::getVar('group', $_SESSION['__USER_GROUP_']);
			unset($_SESSION['__USER_GROUP_']);
			$regHeader = $this->_getRegHeader(4, $userGroup);
			if ($userGroup == GROUP_PAYMENT_MEMBER) {
				$text = SysDBLanguage::_('Signing Up is successful. Your promembership will be checked by admin. Please check your registered email to activate an account.');
			}
			else {
				$text = SysDBLanguage::_('Signing Up is successful. Please check your registered email to activate an account.');
			}
			require SysApplication::getTemplatePath('front/reg/signuptobuy3');
		}


		function _getHtmlPicturesHtmls($userDto, $type='edit') {
			/*	if ($type == 'edit') {
			 $folderPath = "files/images/memberphoto/";
			 //			$folderPath = "files/images/memberphoto/".date('Y/m/d/');
			 }
			 else {
			 //			$itemTpl = SysApplication::loadTemplate('front/modelPictureItem');
			 }*/

			$keyName = "photo";
			if ($type == 'edit') {
				$folderPath = "files/images/memberphoto/";
				$uploadCtrl = $this->_getPictureAjaxUploadControl($keyName, $folderPath, $userDto);
				$uploadCtrlHtml = $uploadCtrl->createUploadFormHtml('', false);
			}
			else {
				$val = $userDto->$keyName;
				$imgLink = RubikHelper::checkAndAddImageURL($val,null, 110);
				$realLink = RubikHelper::checkAndAddImageURL($val);
					
				//			eval('$listCountryHtml .= "'.$itemTpl.'";');
			}
			return $uploadCtrlHtml;
		}

		/**
		 *
		 * @param $inputName
		 * @param $pathFromRoot
		 * @param $valueOrArrayContain
		 * @return AjaxHtmlUploadControl
		 */
		function _getPictureAjaxUploadControl($inputName, $pathFromRoot, $valueOrArrayContain) {
			RExtImporter::cls('ajaxfileupload.AjaxImageHtmlUploadControl');
			$uploadCotrol = new AjaxImageHtmlUploadControl($inputName, $pathFromRoot, $valueOrArrayContain, '*.jpg, *.png, *.gif');
			//		$uploadCotrol->setUploadLabel(SysDBLanguage::_('Upload image', 'general'));
			$uploadCotrol->setUploadLabel('Upload image');

			$uploadCotrol->setUploadUrlProcessing(SystemSite::urlRoute("index.php?app=users&act=ajaxImageUpload&name={$inputName}"));
			$uploadCotrol->setSize(110, 110);
			return $uploadCotrol;
		}

		function ajaxImageUpload() {
			$inputName = SysRequest::getVar('name');
			$ctrl = $this->_getPictureAjaxUploadControl($inputName, null, null);
			echo $ctrl->getAjaxFileResult($_POST);
			exit();
		}

		/**
		 * activate the account
		 *
		 */
		function active() {
			$userName = SysRequest::getVar('ref');
			$userName = @base64_decode($userName);
			$activeCode = SysRequest::getVar('activateCode');
			$activeCode = @base64_decode($activeCode);

			$newPass = SysRequest::getVar('pass');
			$newPass = @base64_decode($newPass);

			$model = $this->_model;
			$dto = $model->activeUser($activeCode, $userName, $newPass);
			if ($dto == false) {
				//			RubikHelper::debugPrePrint($dto);
				$this->setRedirect(SYS_ROOT_URL);
				return;
			}
			$loginLink = SystemSite::urlRoute('?app=authenticate&act=login');
			eval('echo "'.SysApplication::loadTemplate('front/reg/activateSuccessfull').'";');
		}

		function cancel(){
			$this->_setSessionUserInfo(null);
			$this->setRedirectToFunction('registertobuy1');
		}

		function profiles() {
			$type = SysAuthenticate::getUserType();
			switch ($type) {
				case GROUP_PAYMENT_MEMBER:
					$url = SystemSite::urlRoute('?app=member&act=display');
					break;
				case GROUP_FREE_MEMBER:
					$url = SystemSite::urlRoute('?app=newest&act=cate');
					break;
				default:
					$url = SYS_ROOT_URL;
					//				$url = SystemSite::urlRoute('?app=video-chat');
					break;
			}

			$this->setRedirect($url);
			return;
		}
		//==================================================================================================

		/**
		 * xu ly buoc 1: lay du lieu tu SESSION
		 */
		function processRegStep1() {
			$this->_getSessionUserInfo($userDto);
			$result = $this->_userProcess($userDto);
			$this->_setSessionUserInfo($userDto);
			return $result;
		}

		function _getSessionUserInfo(&$userDto) {
			$userDto = $_SESSION['__newuser'];
			if ($userDto) {
				new UserDTO();		//????dong nay khong hieu - lam sao may hieu dc :)) nhung ko co' ko dc ;)
				$userDto = unserialize($userDto);
			}
			if (!$userDto) {
				$userDto = new MemberDTO();
				$userDto->setPaymentGroup();
			}
		}

		/**
		 * Luu cac gia tri userDto vao SESSION
		 */
		function _setSessionUserInfo($userDto) {
			$_SESSION['__newuser'] = serialize($userDto);
		}


		/**
		 * @param $userDto UserDTO
		 * @param $modelDto ModelInfoDTO
		 * @return unknown_type
		 */
		function _userProcess(&$userDto) {
			$userDto->bind($_POST);

			//		$pass = $_POST['new_password'];
			//		$pass = $_POST['password'];
			//		if ($pass !== null) {
			//			$userDto->password = $pass;
			//		} else {
			//			$userDto->password = null;
			//		}

			//		$userDto->checkValidData();

			//check username exist
			if (!$this->_checkExistUser($userDto->username)){
				return "$userDto->username is not available";
			}

			if ($userDto->hasError()) {
				$msg = $userDto->getAllErrorsMsg();
				$userDto->clearAllErrors();
				return $msg;
			}
			return true;
		}



		function _getState(){
			$result = '';
			$myModel = $this->_model;
			$rs = $myModel->getState();
			foreach ($rs as $state){
				$result .= '<option value="'.$state->state_id.'">'.$state->name.'</option>';
			}
			return $result;
		}

		function _getCity(){
			$result = '';
			$myModel = $this->_model;
			$rs = $myModel->getCity();
			foreach ($rs as $city){
				$result .= '<option value="'.$city->city_id.'">'.$city->name.'</option>';
			}
			return $result;
		}

		function getCityOfState(){
			$id = SysRequest::getString("stateid");
			$result = '';
			$myModel = $this->_model;
			$rs = $myModel->getCityOfSate($id);
			foreach ($rs as $city){
				$result .= '<option value="'.$city->city_id.'">'.$city->name.'</option>';
			}
			echo $result;
		}

		function _getAState($id){
			//		RubikHelper::debugPrePrint("sss".$id."sss");
			if ($id === null || $id == "Select a State") return "";
			$myModel = $this->_model;
			$rs = $myModel->getAState($id);
			return $rs->name;
		}

		function _getACity($id){
			//		RubikHelper::debugPrePrint("ccc".$id."ccc");
			if ($id === "" || $id == "Select a City") return "";
			$myModel = $this->_model;
			$rs = $myModel->getACity($id);
			return $rs->name;
		}

		function checkExistUser(){
			$id = SysRequest::getString("username1");
			$myModel = $this->_model;
			$rs = $myModel->checkExistUser($id);
			if ($rs->soluong == 0){
				echo "$id is available";
			} else {
				echo "$id is not available";
			}
		}

		function _checkExistUser($id){
			$myModel = $this->_model;
			$rs = $myModel->checkExistUser($id);
			if ($rs->soluong == 0){
				return true;
			} else {
				return false;
			}
		}

	 function forgot() {
	 	$root = SYS_ROOT_URL;
	 	$templatePath = SYS_CUR_TMPL_URL;
	 	$messageError = '';
	 	if(SysRequest::getMethod() == 'POST') {
	 		$email = SysRequest::getVar('email');
	 		RClassesImporter::cls("dbo.dtos.MemberDTO");
	 		$user = new MemberDTO();
	 		$user->email = $email;
	 		if(!$user->checkExisting('email', true)) {
	 			$messageError = SysLanguage::_('You  input email was not exits on database!');
	 			require SysApplication::getTemplatePath('front/reg/fogotpassword');
	 		} else {
	 			// Send email :D
	 			$activationCode = RStringHelper::generateRandom(32);
	 			$newPass = RStringHelper::generateRandom(12);
	 			$user->password = $newPass;
	 			SysDatabase::saveDTO($user);
	 			 $activationCode = base64_encode($activationCode);
				$ref = base64_encode($user->user_name);
				$pass = base64_encode($newPass);
				$linkActivePass = SystemSite::urlRoute("?app=users&act=active&activateCode={$activationCode}&pass={$pass}&ref={$ref}");
				eval('$mailBody ="'.SysApplication::loadTemplate('front/reg/mail.forgotPass').'";');
	 			
				//RCoreImporter::cls('helper.RMailHelper');
				//$mailBody = "aslkjhaskjhskjahs";
	 		/*	$kq = RMailHelper::sentMail($user->email, "Reset password from Auction.com", $mailBody);
	 			if ($kq) {
	 				eval('echo "'.SysApplication::loadTemplate('front/reg/alldone').'";');
	 			}
	 			else {
	 				eval('echo "'.SysApplication::loadTemplate('front/sendFalse').'";');
	 			}
*/
	 			
	 			$send = $this->smtpmailer($user->email , GUSER, "KBBV", "Reset password from KBBV", $mailBody);
		 		if(!$send)
		        {
		           echo '<p style="text-align:center; margin-top:30px">Send email faile: '.$mail->ErrorInfo."</p>"; 
		            return false;
		        } else {
		        	echo '<p style="text-align:center; margin-top:30px">The email has been sent, please check your email to activate.</p>';
		   			return true;
		        }
	 		}
	 	} else {
	 		require SysApplication::getTemplatePath('front/reg/fogotpassword');
	 	}
	 }
	 
	 /*
	  * if(!$mail->Send())
        {
           echo  'Gởi mail bị lỗi: '.$mail->ErrorInfo; 
            return false;
        } else {
        	
           echo   'The email has been sent, please check your email to activate.';
            return true;
        }
	  * */
	
	function smtpmailer($to, $from, $from_name, $subject, $body)
    {
        global $message;
        $mail = new PHPMailer();                  // tạo một đối tượng mới từ class PHPMailer
        $mail->IsSMTP();                         // bật chức năng SMTP
        $mail->SMTPDebug = 0;                      // kiểm tra lỗi : 1 là  hiển thị lỗi và thông báo cho ta biết, 2 = chỉ thông báo lỗi
        $mail->SMTPAuth = true;                  // bật chức năng đăng nhập vào SMTP này
        $mail->SMTPSecure = 'ssl';                 // sử dụng giao thức SSL vì gmail bắt buộc dùng cái này
        $mail->Host = 'smtp.gmail.com';         // smtp của gmail
        $mail->Port = 465;                         // port của smpt gmail
        $mail->Username = GUSER;  
        $mail->Password = GPWD;           
        $mail->SetFrom($from, $from_name);
        $mail->Subject = $subject;
        $mail->Body = $body;
        $mail->AddAddress($to);
        return $send = $mail->Send();
        
    }
}
